using McpApi.Models;
using System.Text.Json;

namespace McpApi.Services
{
    /// <summary>
    /// 天气影响分析服务 - 分析天气对MES系统的影响并生成预警建议
    /// </summary>
    public class WeatherImpactAnalysisService
    {
        private readonly ILogger<WeatherImpactAnalysisService> _logger;
        private readonly WeatherService _weatherService;
        private readonly MESToolService _mesToolService;
        private readonly IConfiguration _configuration;

        public WeatherImpactAnalysisService(
            ILogger<WeatherImpactAnalysisService> logger,
            WeatherService weatherService,
            MESToolService mesToolService,
            IConfiguration configuration)
        {
            _logger = logger;
            _weatherService = weatherService;
            _mesToolService = mesToolService;
            _configuration = configuration;
        }

        /// <summary>
        /// 分析天气对MES系统的影响
        /// </summary>
        public async Task<MESToolResult> AnalyzeWeatherImpactAsync(Dictionary<string, object> parameters)
        {
            try
            {
                var city = parameters.GetValueOrDefault("city")?.ToString() ?? "Beijing";
                var analysisType = parameters.GetValueOrDefault("analysisType")?.ToString() ?? "comprehensive";
                
                _logger.LogInformation("开始分析天气对MES系统的影响: {City}, {Type}", city, analysisType);

                // 1. 获取天气数据
                var weatherParams = new Dictionary<string, object> { ["city"] = city };
                var currentWeatherResult = await _weatherService.GetCurrentWeatherAsync(weatherParams);
                var forecastResult = await _weatherService.GetWeatherForecastAsync(weatherParams);
                var alertsResult = await _weatherService.CheckWeatherAlertsAsync(weatherParams);

                // 2. 获取MES关键数据
                var mesData = await GetMESKeyDataAsync();

                // 3. 执行影响分析
                var impactAnalysis = await PerformImpactAnalysisAsync(
                    currentWeatherResult.Data as SimpleWeatherInfo,
                    forecastResult.Data as List<SimpleWeatherInfo>,
                    alertsResult.Data as List<WeatherAlert>,
                    mesData,
                    analysisType);

                return new MESToolResult
                {
                    Success = true,
                    Message = "天气影响分析完成",
                    Data = impactAnalysis
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "天气影响分析失败");
                return new MESToolResult
                {
                    Success = false,
                    Message = $"分析失败: {ex.Message}",
                    ErrorCode = "ANALYSIS_ERROR"
                };
            }
        }

        /// <summary>
        /// 生成天气预警报告
        /// </summary>
        public async Task<MESToolResult> GenerateWeatherAlertReportAsync(Dictionary<string, object> parameters)
        {
            try
            {
                var city = parameters.GetValueOrDefault("city")?.ToString() ?? "Beijing";
                var severity = parameters.GetValueOrDefault("severity")?.ToString() ?? "all";
                
                _logger.LogInformation("生成天气预警报告: {City}, 严重程度: {Severity}", city, severity);

                // 获取天气预警
                var weatherParams = new Dictionary<string, object> { ["city"] = city };
                var alertsResult = await _weatherService.CheckWeatherAlertsAsync(weatherParams);
                
                if (alertsResult.Success && alertsResult.Data is List<WeatherAlert> alerts)
                {
                    // 过滤预警级别
                    var filteredAlerts = FilterAlertsBySeverity(alerts, severity);
                    
                    // 生成详细报告
                    var report = await GenerateDetailedAlertReport(filteredAlerts, city);
                    
                    return new MESToolResult
                    {
                        Success = true,
                        Message = $"生成天气预警报告成功，发现 {filteredAlerts.Count} 个预警",
                        Data = report
                    };
                }

                return new MESToolResult
                {
                    Success = true,
                    Message = "当前无天气预警",
                    Data = new { alerts = new List<object>(), summary = "天气状况良好，无需特别关注" }
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成天气预警报告失败");
                return new MESToolResult
                {
                    Success = false,
                    Message = $"报告生成失败: {ex.Message}",
                    ErrorCode = "REPORT_ERROR"
                };
            }
        }

        /// <summary>
        /// 获取天气适应性建议
        /// </summary>
        public async Task<MESToolResult> GetWeatherAdaptationAdviceAsync(Dictionary<string, object> parameters)
        {
            try
            {
                var city = parameters.GetValueOrDefault("city")?.ToString() ?? "Beijing";
                var timeHorizon = parameters.GetValueOrDefault("timeHorizon")?.ToString() ?? "24h";
                
                _logger.LogInformation("获取天气适应性建议: {City}, 时间范围: {TimeHorizon}", city, timeHorizon);

                // 获取天气预报
                var weatherParams = new Dictionary<string, object> { ["city"] = city, ["days"] = GetDaysFromTimeHorizon(timeHorizon) };
                var forecastResult = await _weatherService.GetWeatherForecastAsync(weatherParams);
                
                if (forecastResult.Success && forecastResult.Data is List<SimpleWeatherInfo> forecast)
                {
                    var advice = GenerateAdaptationAdvice(forecast, timeHorizon);
                    
                    return new MESToolResult
                    {
                        Success = true,
                        Message = "生成天气适应性建议成功",
                        Data = advice
                    };
                }

                return new MESToolResult
                {
                    Success = false,
                    Message = "无法获取天气预报数据",
                    ErrorCode = "FORECAST_ERROR"
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取天气适应性建议失败");
                return new MESToolResult
                {
                    Success = false,
                    Message = $"建议生成失败: {ex.Message}",
                    ErrorCode = "ADVICE_ERROR"
                };
            }
        }

        #region 私有方法

        /// <summary>
        /// 获取MES关键数据
        /// </summary>
        private async Task<object> GetMESKeyDataAsync()
        {
            try
            {
                // 并行获取多个MES数据
                var tasks = new[]
                {
                    _mesToolService.QueryProductionOrdersAsync(new Dictionary<string, object> { ["status"] = "进行中" }),
                    _mesToolService.QueryMaterialInventoryAsync(new Dictionary<string, object>()),
                };

                var results = await Task.WhenAll(tasks);
                
                return new
                {
                    productionOrders = results[0].Success ? results[0].Data : null,
                    inventory = results[1].Success ? results[1].Data : null,
                    timestamp = DateTime.UtcNow
                };
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取MES数据时发生错误");
                return new { error = "无法获取MES数据", timestamp = DateTime.UtcNow };
            }
        }

        /// <summary>
        /// 执行影响分析
        /// </summary>
        private async Task<object> PerformImpactAnalysisAsync(
            SimpleWeatherInfo? currentWeather,
            List<SimpleWeatherInfo>? forecast,
            List<WeatherAlert>? alerts,
            object mesData,
            string analysisType)
        {
            await Task.CompletedTask; // 保持异步签名

            var analysis = new
            {
                analysisTime = DateTime.UtcNow,
                analysisType = analysisType,
                weatherSummary = GenerateWeatherSummary(currentWeather, forecast),
                impactAssessment = GenerateImpactAssessment(currentWeather, forecast, alerts),
                mesSystemStatus = AnalyzeMESSystemStatus(mesData),
                recommendations = GenerateRecommendations(currentWeather, forecast, alerts),
                riskLevel = CalculateOverallRiskLevel(alerts),
                actionItems = GenerateActionItems(alerts, mesData)
            };

            return analysis;
        }

        /// <summary>
        /// 生成天气摘要
        /// </summary>
        private object GenerateWeatherSummary(SimpleWeatherInfo? current, List<SimpleWeatherInfo>? forecast)
        {
            if (current == null) return new { error = "无当前天气数据" };

            var next24Hours = forecast?.Where(f => f.DateTime <= DateTime.UtcNow.AddHours(24)).ToList() ?? new List<SimpleWeatherInfo>();
            
            return new
            {
                current = new
                {
                    temperature = current.Temperature,
                    condition = current.Description,
                    windSpeed = current.WindSpeed,
                    humidity = current.Humidity,
                    alertLevel = current.AlertLevel.ToString()
                },
                forecast24h = new
                {
                    temperatureRange = next24Hours.Any() ? 
                        new { min = next24Hours.Min(f => f.Temperature), max = next24Hours.Max(f => f.Temperature) } : null,
                    precipitationProbability = next24Hours.Any() ? 
                        next24Hours.Max(f => f.Precipitation ?? 0) : 0,
                    maxWindSpeed = next24Hours.Any() ? next24Hours.Max(f => f.WindSpeed) : 0
                }
            };
        }

        /// <summary>
        /// 生成影响评估
        /// </summary>
        private object GenerateImpactAssessment(SimpleWeatherInfo? current, List<SimpleWeatherInfo>? forecast, List<WeatherAlert>? alerts)
        {
            var impacts = new List<object>();

            if (current != null)
            {
                // 温度影响
                if (current.Temperature < 0 || current.Temperature > 35)
                {
                    impacts.Add(new
                    {
                        type = "temperature",
                        severity = current.Temperature < -10 || current.Temperature > 40 ? "high" : "medium",
                        description = current.Temperature < 0 ? "低温可能影响设备运行和人员作业" : "高温可能影响设备散热和人员健康",
                        affectedSystems = new[] { "设备运行", "人员作业", "能耗管理" }
                    });
                }

                // 风速影响
                if (current.WindSpeed > 8)
                {
                    impacts.Add(new
                    {
                        type = "wind",
                        severity = current.WindSpeed > 15 ? "high" : "medium",
                        description = "强风可能影响户外作业和物料运输",
                        affectedSystems = new[] { "户外作业", "物料运输", "安全管理" }
                    });
                }

                // 湿度影响
                if (current.Humidity > 85)
                {
                    impacts.Add(new
                    {
                        type = "humidity",
                        severity = "medium",
                        description = "高湿度可能影响电子设备和产品质量",
                        affectedSystems = new[] { "电子设备", "产品质量", "仓储管理" }
                    });
                }
            }

            return new
            {
                totalImpacts = impacts.Count,
                impacts = impacts,
                overallSeverity = impacts.Any(i => i.GetType().GetProperty("severity")?.GetValue(i)?.ToString() == "high") ? "high" : 
                                impacts.Any() ? "medium" : "low"
            };
        }

        /// <summary>
        /// 分析MES系统状态
        /// </summary>
        private object AnalyzeMESSystemStatus(object mesData)
        {
            // 这里可以根据实际的MES数据结构进行分析
            return new
            {
                status = "normal",
                criticalSystems = new[] { "生产线运行正常", "库存水平充足", "设备状态良好" },
                vulnerabilities = new[] { "户外设备可能受天气影响", "运输计划需要调整" }
            };
        }

        /// <summary>
        /// 生成建议
        /// </summary>
        private List<string> GenerateRecommendations(SimpleWeatherInfo? current, List<SimpleWeatherInfo>? forecast, List<WeatherAlert>? alerts)
        {
            var recommendations = new List<string>();

            if (current != null)
            {
                if (current.Temperature < 0)
                {
                    recommendations.Add("检查设备防冻措施，确保管道和设备正常运行");
                    recommendations.Add("调整人员作业时间，避免长时间户外作业");
                }

                if (current.Temperature > 35)
                {
                    recommendations.Add("加强设备散热，监控设备温度");
                    recommendations.Add("调整作业班次，避开高温时段");
                }

                if (current.WindSpeed > 10)
                {
                    recommendations.Add("暂停高空作业，检查户外设备固定");
                    recommendations.Add("调整物料运输计划，确保运输安全");
                }
            }

            if (alerts?.Any() == true)
            {
                recommendations.Add("密切关注天气预警，及时调整生产计划");
                recommendations.Add("准备应急预案，确保人员和设备安全");
            }

            if (!recommendations.Any())
            {
                recommendations.Add("天气状况良好，可正常进行生产作业");
            }

            return recommendations;
        }

        /// <summary>
        /// 计算整体风险级别
        /// </summary>
        private string CalculateOverallRiskLevel(List<WeatherAlert>? alerts)
        {
            if (alerts?.Any(a => a.Level == WeatherAlertLevel.Critical) == true)
                return "critical";
            if (alerts?.Any(a => a.Level == WeatherAlertLevel.High) == true)
                return "high";
            if (alerts?.Any(a => a.Level == WeatherAlertLevel.Medium) == true)
                return "medium";
            if (alerts?.Any(a => a.Level == WeatherAlertLevel.Low) == true)
                return "low";
            
            return "none";
        }

        /// <summary>
        /// 生成行动项目
        /// </summary>
        private List<object> GenerateActionItems(List<WeatherAlert>? alerts, object mesData)
        {
            var actionItems = new List<object>();

            if (alerts?.Any() == true)
            {
                foreach (var alert in alerts)
                {
                    actionItems.Add(new
                    {
                        priority = alert.Level.ToString().ToLower(),
                        action = $"应对{alert.Title}",
                        description = alert.Description,
                        deadline = alert.ValidTo,
                        responsible = "生产管理部",
                        status = "pending"
                    });
                }
            }

            return actionItems;
        }

        /// <summary>
        /// 按严重程度过滤预警
        /// </summary>
        private List<WeatherAlert> FilterAlertsBySeverity(List<WeatherAlert> alerts, string severity)
        {
            return severity.ToLower() switch
            {
                "critical" => alerts.Where(a => a.Level == WeatherAlertLevel.Critical).ToList(),
                "high" => alerts.Where(a => a.Level >= WeatherAlertLevel.High).ToList(),
                "medium" => alerts.Where(a => a.Level >= WeatherAlertLevel.Medium).ToList(),
                "low" => alerts.Where(a => a.Level >= WeatherAlertLevel.Low).ToList(),
                _ => alerts
            };
        }

        /// <summary>
        /// 生成详细预警报告
        /// </summary>
        private async Task<object> GenerateDetailedAlertReport(List<WeatherAlert> alerts, string city)
        {
            await Task.CompletedTask;

            return new
            {
                reportId = Guid.NewGuid().ToString(),
                generatedAt = DateTime.UtcNow,
                location = city,
                alertCount = alerts.Count,
                severityDistribution = alerts.GroupBy(a => a.Level).ToDictionary(g => g.Key.ToString(), g => g.Count()),
                alerts = alerts.Select(a => new
                {
                    id = a.Id,
                    level = a.Level.ToString(),
                    title = a.Title,
                    description = a.Description,
                    impactTypes = a.ImpactTypes.Select(t => t.ToString()).ToArray(),
                    recommendations = a.Recommendations,
                    validPeriod = new { from = a.ValidFrom, to = a.ValidTo }
                }),
                summary = GenerateAlertSummary(alerts)
            };
        }

        /// <summary>
        /// 生成预警摘要
        /// </summary>
        private string GenerateAlertSummary(List<WeatherAlert> alerts)
        {
            if (!alerts.Any())
                return "当前无天气预警，生产可正常进行。";

            var criticalCount = alerts.Count(a => a.Level == WeatherAlertLevel.Critical);
            var highCount = alerts.Count(a => a.Level == WeatherAlertLevel.High);
            var mediumCount = alerts.Count(a => a.Level == WeatherAlertLevel.Medium);

            if (criticalCount > 0)
                return $"发现 {criticalCount} 个严重天气预警，建议立即采取防护措施并考虑暂停相关作业。";
            if (highCount > 0)
                return $"发现 {highCount} 个高级天气预警，建议加强监控并准备应急预案。";
            if (mediumCount > 0)
                return $"发现 {mediumCount} 个中级天气预警，建议关注天气变化并做好准备。";

            return "发现轻微天气预警，建议保持关注。";
        }

        /// <summary>
        /// 生成适应性建议
        /// </summary>
        private object GenerateAdaptationAdvice(List<SimpleWeatherInfo> forecast, string timeHorizon)
        {
            var advice = new List<object>();
            var timeRange = GetTimeRangeFromHorizon(timeHorizon);

            var relevantForecast = forecast.Where(f => f.DateTime <= timeRange).ToList();

            // 分析温度趋势
            if (relevantForecast.Any())
            {
                var minTemp = relevantForecast.Min(f => f.Temperature);
                var maxTemp = relevantForecast.Max(f => f.Temperature);

                if (minTemp < 0)
                {
                    advice.Add(new
                    {
                        category = "temperature_management",
                        priority = "high",
                        title = "低温防护措施",
                        description = $"预计最低温度 {minTemp}°C，需要采取防冻措施",
                        actions = new[] { "检查设备防冻", "准备防寒用品", "调整作业时间" }
                    });
                }

                if (maxTemp > 35)
                {
                    advice.Add(new
                    {
                        category = "temperature_management",
                        priority = "high",
                        title = "高温应对措施",
                        description = $"预计最高温度 {maxTemp}°C，需要采取降温措施",
                        actions = new[] { "加强设备散热", "调整作业班次", "准备防暑用品" }
                    });
                }

                // 分析降水概率
                var maxPrecipitation = relevantForecast.Max(f => f.Precipitation ?? 0);
                if (maxPrecipitation > 0.3)
                {
                    advice.Add(new
                    {
                        category = "precipitation_management",
                        priority = "medium",
                        title = "降雨应对措施",
                        description = $"预计降水概率 {maxPrecipitation:P0}，需要做好防雨准备",
                        actions = new[] { "检查排水系统", "保护户外设备", "调整运输计划" }
                    });
                }
            }

            return new
            {
                timeHorizon = timeHorizon,
                adviceCount = advice.Count,
                advice = advice,
                summary = advice.Any() ? "建议根据天气变化调整生产安排" : "天气状况良好，可按计划进行生产"
            };
        }

        /// <summary>
        /// 从时间范围获取天数
        /// </summary>
        private int GetDaysFromTimeHorizon(string timeHorizon)
        {
            return timeHorizon.ToLower() switch
            {
                "24h" => 1,
                "48h" => 2,
                "72h" => 3,
                "week" => 7,
                _ => 1
            };
        }

        /// <summary>
        /// 从时间范围获取结束时间
        /// </summary>
        private DateTime GetTimeRangeFromHorizon(string timeHorizon)
        {
            return timeHorizon.ToLower() switch
            {
                "24h" => DateTime.UtcNow.AddHours(24),
                "48h" => DateTime.UtcNow.AddHours(48),
                "72h" => DateTime.UtcNow.AddHours(72),
                "week" => DateTime.UtcNow.AddDays(7),
                _ => DateTime.UtcNow.AddHours(24)
            };
        }

        #endregion
    }
}
